package com.news.dao.impl;


import com.news.dao.AdverDao;
import com.news.pojo.Adver;
import com.news.util.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

/**
 * 新闻广告接口实现类
 */
public class AdverDaoImpl implements AdverDao {
    /**
     * 添加广告
     *
     * @param adver
     * @return
     */
    @Override
    public int addAdver(Adver adver) {
        String sql = "INSERT INTO adver(aname,acontent,apicPath)VALUE(?,?,?);";
        Object[] params = {adver.getAname(),adver.getAcontent(),adver.getApicPath()};
        return DBUtil.update(sql,params);
    }

    /**
     * 删除广告
     *
     * @param aid
     * @return
     */
    @Override
    public int delAdver(int aid) {
        String sql = "DELETE FROM adver WHERE aid = ?;";
        Object[] params = {aid};
        return DBUtil.update(sql,params);
    }


    /**
     * 通过id查询广告
     *
     * @param aid
     * @return
     */
    @Override
    public int getAdverByAid(int aid) {
        String sql = "SELECT aid,aname,acontent,apicPath FROM adver WHERE aid = ?;";
        Object[] params = {aid};
        return DBUtil.update(sql,params);
    }

    /**
     * 查询所有广告
     *
     * @return
     */
    @Override
    public List<Adver> getAll() {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        List<Adver> list = new ArrayList<Adver>();
        try{
            //获取连接对象
            conn = DBUtil.getConnection();
            //2.执行sql
            String sql = "SELECT aid,aname,acontent,apicPath FROM adver;";
            //3.获取预处理对象
            pstmt = conn.prepareStatement(sql);
            //5.处理结果集
            rs = pstmt.executeQuery();
            while(rs.next()){
                Adver adver = new Adver();
                adver.setAid(rs.getInt("aid"));
                adver.setAname(rs.getString("aname"));
                adver.setAcontent(rs.getString("acontent"));
                adver.setApicPath(rs.getString("apicpath"));
                list.add(adver);
            }
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            DBUtil.closeAll(conn,pstmt,rs);
        }
        return list;
    }


}
